<?php
// +----------------------------------------------------------------------
// | Tplay [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------


namespace app\admin\model;

use \think\Model;
use \think\db;
use app\api\model\Standard as SDModel;
class Product extends Model
{
    //通过利率和价格刷新总价
    public function refreshProductTotalPrice($product_id)
    {
        //获取产品信息
        $product = db("product")->find($product_id);
        if (empty($product)) return false;
        //获取门票报价
        $scheduleData = (new SDModel())->getProductScheduleData($product['id']);
        $hasTicketPoiId = [];
        foreach ($scheduleData as $key => $value) {
            foreach ($value['children'] as $k => $v) {
                if ($v['ticket_status'] == 1) {
                    $hasTicketPoiId[] = $v['poiid'];
                }
            }
        }
        $ticketTotalCost = 0;
        //价格设置门票价格是否开启 套餐的非用车更新门票
        $pakeage = db('product_package')->where('product_id',$product_id)->find();
        if (!empty($hasTicketPoiId) && !empty($pakeage) && $pakeage['vehicle_type']==2) {
            $ticketData = (new SDModel())->getSectionTicketData($hasTicketPoiId);
            foreach ($ticketData as $ticket_k => $ticket_v) {
                $ticketTotalCost += $ticket_v['unitPrice'];
            }
        }
        $vehicle_rate = $product['vehicle_rate'] ?? 1.25;
        $hotel_rate = $product['hotel_rate'] ?? 1.053;
        $ticket_rate = $product['ticket_rate'] ?? 1.053;
        $extra_rate = $product['extra_rate'] ?? 1.053;
        $extra_fee = $product['extra_fee'] ?? "";
        $extraCost = 0;
        if(!empty($extra_fee) && !empty($product['currency'])){
            $exchange = db('exchange')->where('currency_code',$product['currency'])->find();
            $extra_fee = explode(',',$extra_fee);
            foreach ($extra_fee as $ex_v){
                $extraCost += $ex_v;
            }
            $exchange_rate = $exchange['exchange_rate']??1;
            $extraCost = ceil($extraCost*$exchange_rate*100)/100;
        }
        $dailyprice = db("product_dailyprice pd")
            ->join('product_package p', 'pd.package_id=p.id', 'left')
            ->field('pd.id,pd.vehicle_cost,pd.hotel_cost,pd.ticket_cost,extra_cost,pd.num as people_num')
            ->where(['pd.product_id' => $product_id])->select();
        //开启事务
        db::startTrans();
        try {
            foreach ($dailyprice as $day_key => $day_value) {
                //总售价
                $unitPrice = $this->calculateTotalPrice($day_value['vehicle_cost'], $vehicle_rate, $day_value['hotel_cost'], $hotel_rate, $ticketTotalCost, $ticket_rate, $extraCost, $extra_rate, $day_value['people_num']);
                //更新总价
                db("product_dailyprice")->where(['id' => $day_value['id']])->update([
                    "ticket_cost" => $ticketTotalCost,
                    "extra_cost"=>$extraCost,
                    "price" => $unitPrice
                ]);
            }
            //提交事务
            db::commit();
            return true;
        } catch (Exception $e) {
            //回滚事务
            db::rollback();
            return false;
        }

    }

    //公式计算总价
    public function calculateTotalPrice(
        $vehicleCost,   //用车报价
        $vehicle_rate,  //用车利率
        $hotelCost,     //酒店单价【双人标间】
        $hotel_rate,    //酒店利率
        $ticketCost,    //门票单价
        $ticket_rate,   //门票利率
        $extraCost,     //额外利率
        $extra_rate,    //额外利率
        $peopleNum      //总人数
    )
    {
        $hotelRoomNum = ceil($peopleNum/2);//获取酒店的间数
        $totalVehicleCost = ceil($vehicleCost*$vehicle_rate*100)/100;
        $totalHotelCost = ceil($hotelCost*$hotelRoomNum*$hotel_rate*100)/100;
        $totalTicketCost = ceil($ticketCost*$peopleNum*$ticket_rate*100)/100;
        $totalExtraCost = ceil($extraCost*$extra_rate*100)/100;
        return ceil(($totalVehicleCost+$totalHotelCost+$totalTicketCost+$totalExtraCost)/$peopleNum);
    }


    //更新酒店利率 刷新酒店售价
    public function updHotelCost($product_id,$hotel_rate)
    {
        $product = db("product")->find($product_id);
        if(empty($product_id) || empty($product)) return false;
        $dailyprice = db("product_dailyprice")->where(['product_id'=>$product_id])->select();
        if(!empty($dailyprice)) return false;
        foreach ($dailyprice as $key=>$value){
            if(empty($value['hotel_json'])) continue;

            $hotel_json = json_decode($value['hotel_json'],true);
            if(empty($hotel_json)) continue;

            foreach ($hotel_json as $hotel_k=>$hotele_v){
                $amount = $hotele_v['cost']['amount']??0;
                if(empty($amount)) continue;

                //获取汇率
                $currency_code = $hotele_v['cost']['currency']??"USD";
                $exchange = db("exchange")->where(['currency_code'=>$currency_code])->find();
                $exchange_rate = $exchange['exchange_rate'];

                $hotel_json[$hotel_k]['price']  = sprintf("%.2f",$amount*$exchange_rate*$hotel_rate);
            }

            //刷新价格
            db("product_dailyprice")->where(['id'=>$value['id']])->update(['hotel_json'=>json_encode($hotel_json)]);
        }
    }




}
